package com.itheima.controller;

import com.alibaba.dubbo.config.annotation.Reference;
import com.itheima.constant.MessageConstant;
import com.itheima.constant.RedisConstant;
import com.itheima.entity.PageResult;
import com.itheima.entity.QueryPageBean;
import com.itheima.entity.Result;
import com.itheima.pojo.Setmeal;
import com.itheima.service.SetmealService;
import com.itheima.utils.QiniuUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import redis.clients.jedis.JedisPool;

import java.util.UUID;

@RestController
@RequestMapping("/setmeal")
public class SetmealController {
    @Reference
    private SetmealService setmealService;

    @Autowired
    private JedisPool jedisPool;


    @RequestMapping("/upload")
    public Result upload(@RequestParam("imgFile") MultipartFile imgFile){
        System.out.println(imgFile);
        //得到图片名称
        String originalFilename = imgFile.getOriginalFilename();
        //获取。最后一次出现的位置
        int index = originalFilename.lastIndexOf(".");
        //切割得到
        String substring = originalFilename.substring(index - 1);//类似于.jpr
        //使用UUID生成一个图片名称
        String s = UUID.randomUUID().toString();
        String fileName = s+substring;

        try {
            QiniuUtils.upload2Qiniu(imgFile.getBytes() , fileName);
            jedisPool.getResource().sadd(RedisConstant.SETMEAL_PIC_RESOURCES , fileName);
        }catch (Exception e){
            e.printStackTrace();
            return new Result(false , MessageConstant.PIC_UPLOAD_FAIL);
        }
        return new Result(true , MessageConstant.PIC_UPLOAD_SUCCESS , fileName);
    }

    @RequestMapping("/add")
    public Result add(@RequestBody Setmeal setmeal , Integer [] checkgroupIds){
        try {
            setmealService.add(setmeal , checkgroupIds);
        }catch (Exception e){
            return new Result(false , MessageConstant.ADD_SETMEAL_FAIL);
        }
        return new Result(true , MessageConstant.ADD_SETMEAL_SUCCESS);
    }

    //分页查询,接受传递过来的当前页，每页显示多少条数据，以及查询条件
    @RequestMapping("/findPage")
    public PageResult findPage(@RequestBody QueryPageBean queryPageBean){
        PageResult page = setmealService.findPage(queryPageBean);
        return page;
    }

    //根据id删除套餐
    @RequestMapping("/deleteById")
    public Result deleteById(int id){
        try {
            setmealService.deleteById(id);
        }catch (Exception e){
            e.printStackTrace();
            return new Result(false , MessageConstant.DELETE_SETMEAL_FAIL);
        }
        return new Result(true , MessageConstant.DELETE_SETMEAL_SUCCESS);
    }


}
